package org.jeecg.modules.demo.temple.order.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.TypeReference;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.temple.order.entity.TempleActivityOrder;
import org.jeecg.modules.demo.temple.order.service.ITempleActivityOrderService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.temple.pay.entity.TempleMerchantInfo;
import org.jeecg.modules.demo.temple.pay.service.IJxyhPayService;
import org.jeecg.modules.demo.temple.pay.service.ITempleMerchantInfoService;
import org.jeecg.modules.demo.temple.sys.entity.SysDepart;
import org.jeecg.modules.demo.temple.sys.service.ISysDepart;
import org.jeecg.modules.demo.temple.weixin.entity.TempleUser;
import org.jeecg.modules.demo.temple.weixin.service.ITempleUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 活动订单表
 * @Author: jeecg-boot
 * @Date:   2022-05-06
 * @Version: V1.0
 */
@Api(tags="活动订单表")
@RestController
@RequestMapping("/temple.order/templeActivityOrder")
@Slf4j
public class TempleActivityOrderController extends JeecgController<TempleActivityOrder, ITempleActivityOrderService> {
	@Autowired
	private ITempleActivityOrderService templeActivityOrderService;

	 @Autowired
	 private RedisUtil redisUtil;

	 @Autowired
	 private ITempleMerchantInfoService templeMerchantInfoService;

	 @Autowired
	 private IJxyhPayService jxyhPayService;

	 @Autowired
	 private ITempleUserService templeUserService;

	 @Autowired
	 private ISysDepart sysDepartService;
	/**
	 * 分页列表查询
	 *
	 * @param templeActivityOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "活动订单表-分页列表查询")
	@ApiOperation(value="活动订单表-分页列表查询", notes="活动订单表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TempleActivityOrder>> queryPageList(TempleActivityOrder templeActivityOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		// 判断用户类型
		if (loginUser != null) {
			templeActivityOrder.setSysOrgCode(loginUser.getOrgCode());
		}
		QueryWrapper<TempleActivityOrder> queryWrapper = QueryGenerator.initQueryWrapper(templeActivityOrder, req.getParameterMap());
		Page<TempleActivityOrder> page = new Page<TempleActivityOrder>(pageNo, pageSize);
		IPage<TempleActivityOrder> pageList = templeActivityOrderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param templeActivityOrder
	 * @return
	 */
	@AutoLog(value = "活动订单表-添加")
	@ApiOperation(value="活动订单表-添加", notes="活动订单表-添加")
	@PostMapping({"/add","/api/add"})
	public Result<Map<String,String>> add(@RequestBody TempleActivityOrder templeActivityOrder,HttpServletRequest req) {
		templeActivityOrderService.save(templeActivityOrder);
		TempleMerchantInfo templeMerchantInfo = new TempleMerchantInfo();
		templeMerchantInfo.setSysOrgCode(templeActivityOrder.getSysOrgCode());
		QueryWrapper<TempleMerchantInfo> queryWrapper = QueryGenerator.initQueryWrapper(templeMerchantInfo, req.getParameterMap());
		templeMerchantInfo = templeMerchantInfoService.getOne(queryWrapper);
		String merchantNo = templeMerchantInfo.getMerchantNo();
		String privateKey = templeMerchantInfo.getPrivateKey();
		String publicKey = templeMerchantInfo.getPublicKey();
		String apiKey = templeMerchantInfo.getApiKey();
		String userId = templeActivityOrder.getUserId();
		String sysOrgCode = templeActivityOrder.getSysOrgCode();
		TempleUser user = templeUserService.getById(userId);
		SysDepart depart = new SysDepart();
		depart.setOrgCode(sysOrgCode);
		QueryWrapper<SysDepart> queryWrapper2 = QueryGenerator.initQueryWrapper(depart, req.getParameterMap());
		SysDepart sysDepart = sysDepartService.getOne(queryWrapper2);
		String appId=sysDepart.getWechatMiniAppId();
		String openId = user.getOpenId();
            String transAmt = templeActivityOrder.getAmount().multiply(new BigDecimal("100")).toString();//元转分
//		String transAmt = "1";//调试支付1分钱
		Map orderMap = new HashMap<String,String>();
		try {
			Map<String, String> map = jxyhPayService.payWechatOrder(transAmt,
					templeActivityOrder.getName(),
					templeActivityOrder.getName(),
					"A"+templeActivityOrder.getId(),
					merchantNo,
					"https://godhouse.jxlwtech.com/jeecg-boot/temple.pay/jxyhPayContoller/api/notify",
					"www.baidu.com",
					privateKey,
					publicKey,
					apiKey,
					appId,
					openId);
			orderMap = JSON.parseObject(JSON.toJSONString(templeActivityOrder),new TypeReference<Map<String, String>>() {});
			orderMap.putAll(map);
		}catch (Exception e) {
			e.printStackTrace();
			Result.error("支付失败");
		}
		return Result.OK(orderMap);
	}

	/**
	 *  编辑
	 *
	 * @param templeActivityOrder
	 * @return
	 */
	@AutoLog(value = "活动订单表-编辑")
	@ApiOperation(value="活动订单表-编辑", notes="活动订单表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TempleActivityOrder templeActivityOrder) {
		templeActivityOrderService.updateById(templeActivityOrder);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "活动订单表-通过id删除")
	@ApiOperation(value="活动订单表-通过id删除", notes="活动订单表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		templeActivityOrderService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "活动订单表-批量删除")
	@ApiOperation(value="活动订单表-批量删除", notes="活动订单表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.templeActivityOrderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "活动订单表-通过id查询")
	@ApiOperation(value="活动订单表-通过id查询", notes="活动订单表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TempleActivityOrder> queryById(@RequestParam(name="id",required=true) String id) {
		TempleActivityOrder templeActivityOrder = templeActivityOrderService.getById(id);
		if(templeActivityOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(templeActivityOrder);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param templeActivityOrder
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TempleActivityOrder templeActivityOrder) {
        return super.exportXls(request, templeActivityOrder, TempleActivityOrder.class, "活动订单表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TempleActivityOrder.class);
    }

}
